import React from 'react';
import { hashHistory } from 'react-router';
import { Breadcrumb, Form, Input, Icon, Checkbox, Button, Upload, Modal, message, Table } from 'antd';
import $ from 'jquery';
import Config from '../../common/config';

const FormItem = Form.Item;
const config = new Config();
const token = sessionStorage.getItem('token');
class merchandiseList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      userId: JSON.parse(sessionStorage.getItem('UserInfo')).userid, // 操作人用户ID
      fileList1: [], //上传的商品主图
      fileList5: [], //商品详情页用的5张图片
      fileListHot: [],//热卖商品图
      operation: this.props.params.state, // 操作 add:新增 update:修改
      detail: {}, // 修改详情
      zx_modal: false, //咨询顾问模态框
      product_modal: false, //关联产品模态框
      data_zx: [],
      data_product: [],
      checkId_zx: [],//已选微信号id
      checkId_product: [],//已选热卖产品id
    }
  }

  componentDidMount() {
    this.getdata();
    const operation = this.props.params.state
    if (operation === 'update') {
      const detail = this.props.location.state.data
      console.log(detail, 'detail')
      let checkId_zx = [];
      let checkId_product = [];
      detail.counselors.map((val) => {
        checkId_zx.push(val.id)
      })
      detail.hotData.map((val) => {
        checkId_product.push(val.id)
      })
      const { fileList1, fileList5, fileListHot } = this.state;
      fileList1.push({
        uid: -1,
        name: detail.themeImg,
        status: 'done',
        url: config.Filepath + detail.themeImg,
        thumbUrl: config.Filepath + detail.themeImg,
      });
      if (detail.hotImg) {
        fileListHot.push({
          uid: -1,
          name: detail.hotImg,
          status: 'done',
          url: config.Filepath + detail.hotImg,
          thumbUrl: config.Filepath + detail.hotImg,
        });
      }

      detail.detailImg.split(',').map((item, index) => {
        fileList5.push({
          uid: -(index + 1),
          name: item,
          status: 'done',
          url: config.Filepath + item,
          thumbUrl: config.Filepath + item,
        });
      })
      this.props.form.setFieldsValue({
        title: detail.title,
        classify: detail.classify,
        describe: detail.describe,
        tag: detail.tag,
        themeImg: fileList1,
        detailImg: fileList5,
        hotImg: fileListHot
      })
      this.setState({
        detail,
        fileList1,
        fileList5,
        checkId_zx,
        checkId_product
      })
    }
    $('.rdw-image-wrapper .rdw-option-wrapper').click(
      (e) => {
        $('#xFile').trigger('click');
        $('.rdw-image-modal').focus();
      }
    );
  }

  // 获取数据
  getdata() {
    let data = { pageSize: 10000 };
    if (this.props.params.state == 'update') {
      console.log(this.props.location.state.data.id)
      data.id = this.props.location.state.data.id
    }

    $.ajax({ //获取咨询顾问数据
      url: `${config.jusewebsite_zml}/counselor/list`,
      type: 'get',
      headers: {
        'Authorization': 'Bearer ' + token,
      },
      data: {
        pageSize: 10000
      },
      success: (res) => {
        console.log('111', res)
        if (res.code === 200) {
          // res.data.rows.forEach((item, index) => {
          //   item.key = index + 1 + (this.state.page - 1) * this.state.pageSize;         
          // })
          this.setState({
            // total: res.data.count,
            data_zx: res.data.rows
          })
        }
      }
    });
    console.log(this.state.data_zw)
    $.ajax({
      url: `${config.jusewebsite_zml}/product/nonHotList`,
      type: 'get',
      headers: {
        'Authorization': 'Bearer ' + token,
      },
      data,
      success: (res) => {
        console.log(res)
        if (res.code === 200) {
          this.setState({
            data_product: res.data.rows
          })
        }
      }
    })
    console.log(this.state.data_product, '产品')
  }

  //富文本编辑器图片上传
  upload(e) {
    const formData = new FormData(); //创建一个form表单对象
    formData.append('Filedata', e.target.files[0]); //表单对象压入图片
    if (e.target.files.length) {

      const xhr = new XMLHttpRequest();
      xhr.open('POST', config.UploadFile + '/websitProductImg');
      xhr.send(formData);
      xhr.addEventListener('load', () => {
        const response = JSON.parse(xhr.responseText);
        if (response.code == 200) {
          this.setState({
            imageFile: response.data
          }, () => {
            $('.rdw-image-modal-url-input')[0].value = config.Filepath + response.data;
            $('.rdw-image-modal-size .rdw-image-modal-size-input')[1].value = '100%';
            $('.rdw-image-modal-url-input').focus();
            $('.rdw-image-modal-url-input').blur();
          });
        }
      });
      xhr.addEventListener('error', () => {
        const error = JSON.parse(xhr.responseText);
      });
    }
  }

  //限制用户必须上传图片格式的文件、图片大小
  beforeUpload(file, fileList) {
    let isIMG = file.type.indexOf('image') != -1;
    if (!isIMG) {
      message.config({ top: 50 });
      message.error('您只能上传图片！');
    }
    let isLt10M = file.size / 1024 / 1024 < 10;
    if (!isLt10M) {
      message.config({ top: 50 });
      message.error('您上传的图片大小必须小于10MB！');
    }
    return isIMG && isLt10M;
  }

  //上传图片
  normFile1(e) {
    this.setState({
      fileList1: e.fileList
    });
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };


  //上传图片
  normFile5(e) {
    this.setState({
      fileList5: e.fileList
    });
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };
  //上传图片
  normFileHot(e) {
    this.setState({
      fileListHot: e.fileList
    });
    if (Array.isArray(e)) {
      return e;
    }
    return e && e.fileList;
  };

  // 新增或修改
  save(e) {
    e.preventDefault()
    this.props.form.validateFields((err, values) => {
      console.log(values)
      if (!err) {
        let url = `${config.jusewebsite_zml}/product`
        const data = {
          themeImg: values.themeImg[0].response ? values.themeImg[0].response.data : values.themeImg[0].name,
          title: values.title,
          classify: values.classify,
          describe: values.describe,
          tag: values.tag,
          detailImg: values.detailImg.map(item => item.response ? item.response.data : item.name).join(','),
          productHotId: this.state.checkId_product.toString(),
          counselorIds: this.state.checkId_zx.toString(),
          // hotImg:values.hotImg[0].response ? values.hotImg[0].response.data : values.hotImg[0].name,
          //          hotImg:values.hotImg==undefined?null:values.hotImg[0].response.data
          //         hotImg:values.hotImg[0].response ? values.hotImg[0].response.data : values.hotImg[0].name,
        }
        if (values.hotImg == undefined || values.hotImg.length == 0) {
          data.hotImg = null

        } else {
          data.hotImg = values.hotImg[0].response ? values.hotImg[0].response.data : values.hotImg[0].name
        }

        if (this.state.operation === 'add') {
          url += '/add'
        } else {
          url += '/update'
          data.id = this.state.detail.id
        }
        $.ajax({
          url,
          type: 'post',
          data,
          headers: {
            'Authorization': 'Bearer ' + token,
          },
          success: res => {
            console.log('操作产品', res)
            if (res.code === 200) {
              message.success(res.mes)
              this.linkPrev()
            }
          }
        })
      }
    })
  }

  // 跳转上一个页面
  linkPrev() {
    if (this.state.operation === 'add') {
      hashHistory.push({ pathname: '/merchandiseList_zml' })
    } else {
      const paths = {
        pathname: '/merchandiseList_zml',
        state: this.props.location.state
      };
      hashHistory.push(paths);
    }
  }
  // 关闭咨询顾问模态框
  zxClose() {
    this.setState({
      zx_modal: false,
      checkId_zx: [],
    })
  }
  // 显示模态框
  showModal(tip) {
    if (tip == 0) {
      this.setState({
        zx_modal: true
      })
    } else {
      this.setState({
        product_modal: true
      })
    }
  }


  removeByValue(arr, val) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] == val) {
        arr.splice(i, 1);
        break;
      }
    }
  }

  handleChange_zx(id, e) {

    if (e.target.checked) {
      console.log(id, '选中')
      let checkedArray = this.state.checkId_zx;
      let checkId_zx = [...checkedArray, id]
      this.setState({
        checkId_zx
      })
    } else {
      let checkedArray = this.state.checkId_zx;
      console.log(checkedArray)
      this.removeByValue(checkedArray, id)
      console.log(checkedArray)
      this.setState({
        checkId_zx: checkedArray
      })
      console.log(this.state.checkId_zx)
    }
  }
  handleChange_product(id, e) {
    if (e.target.checked) {
      console.log(id, '选中')
      let checkedArray = this.state.checkId_product;
      let checkId_product = [...checkedArray, id]
      this.setState({
        checkId_product
      })
    } else {
      let checkedArray = this.state.checkId_product;
      console.log(checkedArray)
      this.removeByValue(checkedArray, id)
      console.log(checkedArray)
      this.setState({
        checkId_product: checkedArray
      })
      console.log(this.state.checkId_product)
    }
  }


  // 选择默认
  checkini(id, tip, e) {
    // console.log(id,tip,'选择默认')
    // const checkId_zx=this.state.checkId_zx;
    // const checkId_product=this.state.checkId_product;
    // if(tip===0){
    //   if(checkId_zx.indexOf(id)!==(-1)){
    //     return false
    //   }else{
    //     return false
    //   }
    // }else{
    //   if(checkId_product.indexOf(id)!==(-1)){
    //     return false
    //   }else{
    //     return false
    //   }
    // }
    return 'false'
  }


  render() {
    const { getFieldDecorator } = this.props.form;
    const { zx_modal, product_modal } = this.state;
    const formItemLayout = { labelCol: { span: 3 }, wrapperCol: { span: 21 } };
    const tailFormItemLayout = {
      wrapperCol: {
        xs: {
          span: 24,
          offset: 0,
        },
        sm: {
          span: 14,
          offset: 3,
        },
      },
    };

    const columns_zx = [
      {
        title: '操作',
        width: '50%',
        render: record => {
          return <p>
            <Checkbox
              onChange={this.handleChange_zx.bind(this, record.id)}
              defaultChecked={this.state.checkId_zx.indexOf(record.id) !== -1 ? true : false}
            >
              选择
          </Checkbox>
          </p>
        }
      },
      {
        title: '微信号',
        width: '50%',
        dataIndex: 'weChatId'
      }
    ]

    const columns_product = [
      {
        title: '操作',
        width: '50%',
        render: record => {
          return <p>
            <Checkbox
              onChange={this.handleChange_product.bind(this, record.id)}
              defaultChecked={this.state.checkId_product.indexOf(record.id) !== -1 ? true : false}
            >
              选择
        </Checkbox>
          </p>
        }
      },
      {
        title: '热卖商品',
        width: '50%',
        dataIndex: 'title'
      }
    ]

    return (

      <div className='contentBox clearfix' style={{ height: '140%' }}>
        <Modal
          className='zx-modal'
          title='咨询顾问'
          visible={zx_modal}
          okText='添加'
          cancelText='取消'
          onCancel={() => { this.setState({ zx_modal: false }) }}
          onOk={() => { this.setState({ zx_modal: false }) }}
        >
          <Table columns={columns_zx} dataSource={this.state.data_zx} pagination={false} bordered />

        </Modal>
        <Modal
          className='product-modal'
          title='热卖产品'
          visible={product_modal}
          okText='添加'
          cancelText='取消'
          onCancel={() => { this.setState({ product_modal: false }) }}
          onOk={() => { this.setState({ product_modal: false }) }}
        >
          <Table columns={columns_product} dataSource={this.state.data_product} pagination={false} bordered />
        </Modal>
        <div className="member-content-Search">
          <div className='breadcrumb'>
            <Breadcrumb separator=">">
              <Breadcrumb.Item>官网管理</Breadcrumb.Item>
              <Breadcrumb.Item>脂玫乐</Breadcrumb.Item>
              {
                this.state.operation === 'add'
                  ?
                  <Breadcrumb.Item>新增</Breadcrumb.Item>
                  :
                  <Breadcrumb.Item>修改</Breadcrumb.Item>
              }
            </Breadcrumb>
            <div className="ctoutd" style={{ width: '50%', marginTop: 50 }}>
              <Form onSubmit={this.save.bind(this)} >
                <FormItem
                  label="主图"
                  {...formItemLayout}
                >
                  {getFieldDecorator('themeImg', {
                    valuePropName: 'fileList1', getValueFromEvent: this.normFile1.bind(this),
                    rules: [{ required: true, message: '请上传商品图片！' }],
                  })(
                    <Upload
                      accept="image/*"
                      name="img"
                      action={config.UploadFile + "/websitProductImg"}
                      beforeUpload={this.beforeUpload.bind(this)}
                      listType="picture"
                      className="upload-list-inline onepicture"
                      defaultFileList={this.state.fileList1}
                    >
                      {
                        this.state.fileList1.length >= 1 ? null :
                          <Button><Icon type="upload" /> 上传图片</Button>
                      }
                    </Upload>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="标题"
                  hasFeedback
                >
                  {getFieldDecorator('title', {
                    rules: [{
                      required: true, message: '请填写标题!',
                    }, {
                      validator: this.checkConfirm,
                    }],
                  })(
                    <Input type="title" />
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="描述"
                  hasFeedback
                >
                  {getFieldDecorator('describe', {
                    rules: [{
                      required: true, message: '请填写描述!',
                    }, {
                      validator: this.checkConfirm,
                    }],
                  })(
                    <Input type="describe" />
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="分类"
                  hasFeedback
                >
                  {getFieldDecorator('classify', {
                    rules: [{
                      required: true, message: '请填写分类!',
                    }, {
                      validator: this.checkConfirm,
                    }],
                  })(
                    <Input type="classify" />
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="标签"
                  hasFeedback
                >
                  {getFieldDecorator('tag', {
                    rules: [{
                      message: '请填写标签!',
                    }, {
                      validator: this.checkConfirm,
                    }],
                  })(
                    <Input type="tag" />
                  )}
                </FormItem>
                <FormItem
                  label="内容编辑"
                  {...formItemLayout}
                >
                  {getFieldDecorator('detailImg', {
                    valuePropName: 'fileList5', getValueFromEvent: this.normFile5.bind(this),
                    rules: [{ required: true, message: '请上传商品图片！' }],
                  })(
                    <Upload
                      accept="image/*"
                      name="img"
                      action={config.UploadFile + "/websitProductImg"}
                      beforeUpload={this.beforeUpload.bind(this)}
                      listType="picture"
                      className="upload-list-inline fivepicture onepicture"
                      defaultFileList={this.state.fileList5}
                      multiple={true}
                    >
                      {
                        this.state.fileList5.length >= 10 ? null :
                          <Button><Icon type="upload" /> 上传图片</Button>
                      }
                    </Upload>

                    // <div className="clearfix">
                    //     <Upload
                    //         action="//jsonplaceholder.typicode.com/posts/"
                    //         listType="picture-card"
                    //         fileList={fileList}
                    //         onPreview={this.handlePreview}
                    //         onChange={this.handleChange}
                    //     >
                    //         {this.state.fileList5.length >= 3 ? null : uploadButton}
                    //     </Upload>
                    //     <Modal visible={previewVisible} footer={null} onCancel={this.handleCancel}>
                    //         <img alt="example" style={{ width: '100%' }} src={previewImage} />
                    //     </Modal>
                    // </div>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="咨询顾问"
                >
                  {getFieldDecorator('zxgw', {
                    rules: [
                      //   {
                      //   required: true, message: '请选择咨询顾问!',
                      // }, 
                      // {
                      //   validator: this.checkConfirm,
                      // }
                    ],
                  })(
                    <Button type='parmary' onClick={() => this.showModal(0)} >{this.state.checkId_zx.length === 0 ? '选择' : '已选'}</Button>
                  )}
                </FormItem>
                <FormItem
                  {...formItemLayout}
                  label="热卖产品"
                >
                  {getFieldDecorator('rmcp', {
                    rules: [
                      //   {
                      //   required: true, message: '请选择热卖产品!',
                      // }, 
                      // {
                      //   validator: this.checkConfirm,
                      // }
                    ],
                  })(
                    <Button type='parmary' onClick={() => this.showModal(1)} >{this.state.checkId_product.length === 0 ? '选择' : '已选'}</Button>
                  )}
                </FormItem>
                <FormItem
                  label="该热卖商品图"
                  {...formItemLayout}
                >
                  {getFieldDecorator('hotImg', {
                    valuePropName: 'fileListHot', getValueFromEvent: this.normFileHot.bind(this),
                    rules: [{ required: true, message: '请上传热卖商品图片！' }],
                  })(
                    <Upload
                      accept="image/*"
                      name="img"
                      action={config.UploadFile + "/websitProductImg"}
                      beforeUpload={this.beforeUpload.bind(this)}
                      listType="picture"
                      className="upload-list-inline onepicture"
                      defaultFileList={this.state.fileListHot}
                    >
                      {
                        this.state.fileListHot.length >= 1 ? null :
                          <Button><Icon type="upload" /> 上传图片</Button>
                      }
                    </Upload>
                  )}
                </FormItem>
                <FormItem {...tailFormItemLayout}>
                  <Button type="primary" htmlType="submit" size="small" style={{ width: '100px', height: '35px' }}>确定</Button> <Button style={{ width: '100px', height: '35px' }} onClick={this.linkPrev.bind(this)} size="small">取消</Button>
                </FormItem>

              </Form>
            </div>
          </div>
        </div>
      </div>
    )
  }
}

export default Form.create()(merchandiseList);
